/**
 * 
 */
var path = '../';
var pageListUrl = path + 'sdkInfo/list';
var pageUrl = path + 'sdkInfo/';

//添加弹窗
var addPanel = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var sdkInfo={
	checkLogic:function(dataObj){
		//清除历史错误提示
        dataObj.sdkCodeErr="";
        dataObj.sdkNameErr="";
        dataObj.priorityErr="";
        dataObj.areasErr="";

		var result="";
		var isSubmit=true;
		//TODO 逻辑校验，去掉不必要的:

		result=customUtils.checkLen(dataObj.sdkName,1,32,'SDK名称');
		if(result.length!=0){
			dataObj.sdkNameErr=result;
			isSubmit=false;
		}

		var reg = /^\d$/;
		if(!reg.test(dataObj.priority)){
			dataObj.priorityErr="优先级必须是1位数字";
			isSubmit=false;
		}

	    //检查表单是否存在错误
		$.each(dataObj, function(key) {
			if(key.indexOf('Err')!=-1 && dataObj[key].length>0){
				return false;
			}									 
		});
		return isSubmit;
	},
    setCitys:function () {
        addOrUpdate.$data.city = "";
        addOrUpdate.$data.area = "";

    },
    setAreas:function () {
        addOrUpdate.$data.area = "";

    }
};

//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立 
var dataList=new Vue({
	el:"#sdkInfoList",
	data:{
		pageInfo : {},
		//TODO 自定义条件查询---begin--------			
		condition:{
			page:1,
			rows:customUtils.pageSize,
		    id:"",
		    sdkCode:"",
		    sdkName:"",
		    priority:"",
            provinces:[],

		    areas:"",
		    createdBy:"",
		    createdDate:"",
		    updatedBy:"",
		    updatedDate:"",
		    status:"",
		},
		//自定义条件查询---end--------
		selectIds:[],//多选
		showSuccess:false,//false不显示成功提示
		selectedIdx:-1,//保存操作行的索引
		isSearch:false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
		selectedPageSize:customUtils.pageSize//修改页面数据显示条数
	},
	mounted: function () {
		//初始化页面数据
		this.getList('init');
		this.getAreaData();
	},
	// 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
	methods:{
	    selectChkBtn:function(e){//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        getAreaData:function () {
            this.$http.get("../appInfo/queryAreaTree").then(function(response){
                console.log(response);
                addOrUpdate.$data.provinces = response.body;
                console.log(addOrUpdate.$data)
            },function (res) {
                customUtils.showRequestTips(res,2000)
            });
        },
		//搜索、分页列表
		getList:function(eventSrc){				
			var self=this;
			//改变页面显示条数
			if(eventSrc=="changePageSize"){
				if(this.pageInfo.pageSize != this.selectedPageSize){
					this.pageInfo.pageSize=this.selectedPageSize;
					$('#pagination').jqPaginator('destroy');
					eventSrc='init';//重新绘制控件
				}else{
					return;
				}
			}				
			//初始化时无当前页数，后台有默认第1页，每页10条
			if(this.pageInfo!=undefined && this.pageInfo.pageNum!=undefined){
				self.condition["page"]=this.pageInfo.pageNum;
				self.condition["rows"]=this.pageInfo.pageSize;
			}
			//发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
			customUtils.post(self,pageListUrl,self.condition,function(response,isSuccess){ 
				if(isSuccess==false){
				    dataList.pageInfo.pages=0;
				    customUtils.noData('无数据',0);
				    return;
				}
				dataList.pageInfo = response.body.pagination;
				customUtils.noData('无数据',dataList.pageInfo.pages);
				//页面初始化、搜索时，才需要执行分页控件
				if(eventSrc=='init' || eventSrc=='search'){
					customUtils.paging('#pagination',dataList.pageInfo.pages,customUtils.showPage,function(num){
						//当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
						if(dataList.pageInfo.pageNum!=num){			    	
					    	dataList.pageInfo.pageNum=num;
							dataList.getList('paging');	
						}							    	
				    });
				}
            },function(response){
                console.log(response);
                dataList.pageInfo.pages=0;
			    customUtils.noData('无数据',0);
            });						
		},	
		//更新状态
		updateStatus:function(index){
			var record = this.pageInfo.list[index];
			var status = record.status==1?0:1;
			var param = {id:record.id,status:status};
			var self=this;
			customUtils.post(self,pageUrl + 'update',param,function(response,isSuccess){ 
				record.status=status;
				//根据需要刷新页面数据
				dataList.getList('no');
            },function(response){
                //console.log(response.body);
            });			
		},
		//初始化更新，更新对话框
		updateInit:function(index){
			//先显示窗口，才有加载效果
			this.addOrUpdatePanel("update");
			var record = this.pageInfo.list[index];
			this.selectedIdx=index;
			var url = pageUrl + 'id/'+record.id;
			var self=this;
			customUtils.get(self.$http,url,function(response,isSuccess){ 
				if(isSuccess==false){
				    return;
				}
				//回显表单数据
				$.each(response.body, function(key) {
					if(addOrUpdate[key]!==undefined && response.body[key]){
						addOrUpdate[key] = response.body[key];
					}									 
				});

                addOrUpdate.$data.areaList = JSON.parse(addOrUpdate.$data.areas);
                var list = addOrUpdate.$data.areaList;
                addOrUpdate.$data.areas = [];
                for (var i = 0; i< list.length; i++) {
                    addOrUpdate.$data.areas.push(list[i].code);
				}
            },function(response){
                console.log(response);
            });
		},
		//打开添加对话框
		addOrUpdatePanel:function(flag){
		    //清除表单数据，否则会有前一条修改数据的内容
            addOrUpdate.$data.sdkCode= "";
            addOrUpdate.$data.sdkName= "";
            addOrUpdate.$data.priority= "";
            addOrUpdate.$data.areas= [];
            addOrUpdate.$data.areaList= [];
            addOrUpdate.$data.id= "";

            addOrUpdate.$data.province= "";
            addOrUpdate.$data.city= "";
            addOrUpdate.$data.area= "";

            if(flag == 'update'){
            	$("#addPanel").find("input[name='sdkName']").prop("readonly",true);
			}else{
                $("#addPanel").find("input[name='sdkName']").prop("readonly",false);
			}


			var tmpTitle =  flag=="add"?"添加":"修改";
			addPanel = layer.open({
				type : 1,
				title :tmpTitle+"SDK管理",
				area : [ '570px', 'auto' ],
				shadeClose : false, // 点击遮罩关闭
				content : $('#addPanel')
			});
		}
	}
});
//绑定列表List---end---- 

//新增或更新---------begin-------
var addOrUpdate = new Vue({
	el:"#addPanel",
	data:{
		sdkCode:"",
		sdkName:"",
		priority:"",
		areas:[],
        areaList:[],
        id:"",

        provinces:[],
        province:"",
        city:"",
        area:"",


		updatedBy:"",
		updatedDate:"",
		status:"",

		//以下是错误信息
		sdkCodeErr:"",
		sdkNameErr:"",
		priorityErr:"",
		areasErr:"",

		updatedByErr:"",
		updatedDateErr:"",
		statusErr:"",
	showSuccess:true,//显示成功提示
	},
	//当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch:{
    },
	methods:{		
	    changeTime:function(elem){
			addOrUpdate[elem.split('-')[0]] = $("#"+elem).val();               
		},
        addArea:function () {
	    	var area = this.$data.area;
	    	var city = this.$data.city;
	    	var province = this.$data.province;
			if(area && area != "" && area != null){
                addOrUpdate.pushNoRepeat(this.$data.area);
			}else if(city && city != "" && city != null) {
				$.each(city.areas ,function(i){
                    addOrUpdate.pushNoRepeat(city.areas[i]);
				});
			}else if(province && province != "" && province != null){
				$.each(province.citys,function (i) {
					$.each(province.citys[i].areas,function (j) {
                        addOrUpdate.pushNoRepeat(province.citys[i].areas[j]);
                    });
                })
			}
        },
		//避免重复添加
		pushNoRepeat:function(area){
	    	var fg = true;
            for (var i = 0; i< addOrUpdate.$data.areas.length; i++){
               if(addOrUpdate.$data.areas[i] == area.code){
					fg = false;
					break;
			   }
			}
			if(fg){
                addOrUpdate.$data.areas.push(area.code);
                addOrUpdate.$data.areaList.push(area)
			}
		},
        cloce:function (code) {
	    	var index;
	    	for (var i = 0; i<addOrUpdate.$data.areaList.length; i++ ) {
                if(addOrUpdate.$data.areaList[i].code == code){
                    index = i;
                    break;
                }
			}
            addOrUpdate.$data.areaList.splice(index,1);
	    	addOrUpdate.$data.areas.splice($.inArray(code, addOrUpdate.$data.areas), 1);
        },
		save:function(){
			//逻辑校验
			if(!sdkInfo.checkLogic(this.$data)){
				return;
			}
			//没有id的时候表示新增，否则为更新
			var actionUrl=this.id=="" ? 'save' :'update';
			var self=this;
			self.$data.areas = JSON.stringify(self.$data.areas);
			customUtils.post(self,pageUrl + actionUrl,self.$data,function(response,isSuccess){ 
				if(actionUrl=='update'){
					var record = dataList.pageInfo.list[dataList.selectedIdx];
					//更新成功，刷新列表中对应的数据
					$.each(record, function(key) {
						if(addOrUpdate[key]!=undefined){
							record[key]=addOrUpdate[key];
						}									 
					});						
				}else if(isSuccess){

				}
                dataList.getList('init');
				if(isSuccess && addPanel)layer.close(addPanel);
			},function(res){
                //console.log(response.body);
            });			
		},
		setCitys:function () {
			sdkInfo.setCitys();
        },
		setAreas:function () {
			sdkInfo.setAreas();
        },
		//清除表单数据
		reset:function(){
            if(addPanel)layer.close(addPanel);
	    }
	}
});
//新增或更新---------end-------
